<template>
  <div class="add-address">
    <div class="sticky left-0 right-0 top-0 z-9 h-full bg-hex-ffffff px-28rpx pb-32rpx">
      <div class="z-999 flex items-center justify-between" :style="{ paddingTop: `${searchBarTop}px` }" @click.stop="goback">
        <uni-icons type="back" size="28" />
        <span class="flex-1 text-36rpx" style="text-align: center;">添加地址</span>
      </div>
    </div>
    <div class="mx-32rpx mt-74rpx">
      <uni-forms ref="formRef" :model-value="addressForm" :rules="rules" class="text-28rpx font-500 text-hex-333">
        <uni-forms-item required label="联系人" name="name" :labelWidth="80"
                        class="border-2rpx border-transparent border-b-hex-f5f5f5 border-solid">
          <uni-easyinput v-model="addressForm.name" placeholder="请输入联系人姓名" :inputBorder="false"
                         placeholderStyle="color:#999999;font-size:28rpx" />
        </uni-forms-item>
        <uni-forms-item required label="性别" name="sex" :labelWidth="80"
                        class="border-2rpx border-transparent border-b-hex-f5f5f5 border-solid">
          <uni-data-checkbox v-model="addressForm.sex" :localdata="[{
            text: '先生',
            value: 1,
          }, {
            text: '女士',
            value: 0,
          }]" />
        </uni-forms-item>
        <uni-forms-item required label="手机号" name="mobile" :labelWidth="80"
                        class="border-2rpx border-transparent border-b-hex-f5f5f5 border-solid">
          <uni-easyinput v-model="addressForm.mobile" type="number" placeholder="请输入联系人手机号" :inputBorder="false"
                         placeholderStyle="color:#999999;font-size:28rpx" />
        </uni-forms-item>
        <uni-forms-item required label="收货地址" :labelWidth="80"
                        class="border-2rpx border-transparent border-b-hex-f5f5f5 border-solid">
          <div class="flex items-center" @click="open">
            <div v-if="addressForm.address!==''" class="ml-18rpx flex-1">{{ addressForm.address }}</div>
            <div v-else class="ml-18rpx flex-1 text-hex-999">请输入收货地址</div>
          </div>
        </uni-forms-item>
        <uni-forms-item required label="门牌号" name="detail" :labelWidth="80"
                        class="border-2rpx border-transparent border-b-hex-f5f5f5 border-solid">
          <div class="flex items-center">
            <uni-easyinput v-model="addressForm.detail" placeholder="请输入门牌号" :inputBorder="false"
                           placeholderStyle="color:#999999;font-size:28rpx" />
            <div v-if="isNotNilOrEmpty(location.selectStores.distance)" class="ml-15rpx w-50rpx" @click.stop="navTo('/pages-mine/positioning')">
              <image :src="`${cdnUrl}/imgs/shop/cityIcon.png${imgVersion}`" class="h-30rpx w-27rpx" />
            </div>
            <div v-else class="text-hex-2979ff" @click="Reposition">重新定位</div>
          </div>
        </uni-forms-item>
        <uni-forms-item label="地址标签" :labelWidth="80" class="flex border-2rpx border-transparent border-b-hex-f5f5f5 border-solid">
          <div class="h-36rpx flex items-center">
            <div
              v-for="item in tagList"
              :key="item.id"
              :class="{ tabActive: tagIndex===item.id }"
              class="ml-20rpx h-36rpx w-64rpx border-1rpx border-hex-999999 rounded-6rpx border-solid text-center text-24rpx leading-36rpx text-hex-999999"
              @click="changetagIndex(item.id)">
              {{ item.text }}
            </div>
          </div>
        </uni-forms-item>
        <uni-forms-item label="设为默认地址" :labelWidth="140" class="border-2rpx border-transparent border-b-hex-f5f5f5 border-solid">
          <div text-right>
            <switch style="width:112rpx" :checked="checked" color="#ABCD03" class="switch-color" @change="setDefealt" />
          </div>
        </uni-forms-item>
      </uni-forms>
      <city-picker
        :defaultValue="location.locationInfo.adcode"
        :mask-close-able="maskCloseAble"
        :visible="visible"
        :city="location.locationInfo.city"
        @cancel="onCancel"
        @confirm="confirm" />
    </div>
    <div
      class="fixed bottom-35rpx left-0 right-0 mx-32rpx h-72rpx rounded-46rpx bg-hex-ABCD03 text-center leading-72rpx text-hex-ffffff"
      @click="save"
    >{{ edittype ==='1'?'编辑':'保存' }}</div>
  </div>
</template>

<script lang="ts" setup>
import cityPicker from './components/cityPicker.vue'
import { useAddressStore } from '@/stores/address'
import { useUserStore } from '@/stores/user'

const { user } = useUserStore()
let location = useAddressStore()
let searchBarTop: any = $ref('24')
let formRef: any = $ref()
let editId = $ref('')
let edittype = $ref('')
onLoad((options) => {
  if (options) {

    editId = options.id
    edittype = options.edit
  }
  // #ifndef H5
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  searchBarTop = menuButtonInfo.top
  // #endif
})

const goback = () => {
  location.clearIocationInfo()
  uni.navigateBack({
    delta: 1,
  })
}
const addressForm = $ref({
  name: '',
  mobile: '',
  detail: '',
  address: '',
  sex: 1,
})
const rules = $ref({
  name: {
    rules: [{
      required: true,
      errorMessage: '名字不能为空',
    }],
  },
  mobile: {
    rules: [{
      required: true,
      errorMessage: '手机号不能为空',
    }, {
      validateFunction(rule, value, data, callback) {
        let iphoneReg = (/^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/) //手机号码
        if (!iphoneReg.test(value)) {
          callback('手机号码格式不正确，请重新填写')
        }
      },
    }],
  },
  detail: {
    rules: [{
      required: true,
      errorMessage: '请填写信息地址',
    }],
  },
})
watch(() => location.locationInfo, () => {
  let { province, city, district, detailAddress } = location.locationInfo
  visible = false
  addressForm.address = province + city + district
  addressForm.detail = detailAddress
})
let checked: any = $ref(true)
const setDefealt = (e) => {
  checked = e.detail.value
}
//重新定位打开定位服务
const Reposition = () => {
  uni.getSetting({
    success: (res) => {
      // 如果用户已经授权定位权限
      if (!res.authSetting['scope.userLocation']) {
        uni.showModal({
          title: '授权提示',
          content: '需要获取您的位置信息，请点击下方按钮进入设置页面进行授权',
          confirmText: '去设置',
          success(res) {
            if (res.confirm) {
              uni.openSetting({
                success(res) {
                  if (res.authSetting['scope.userLocation']) {
                    location.updateEmpower(true)
                    location.getPosition({})
                    navTo('/pages-mine/positioning')
                  }
                },
                fail(err) {
                  console.log(err)
                },
              })
            }
          },
        })
      }
    },
  })
}
//保存地址
const save = () => {
  formRef.validate().then(async () => {
    if (edittype === '1') {
      location.edit_save('1', user.id, {
        ...addressForm,
        isDefault: checked ? 1 : 0,
        gender: Number(addressForm.sex),
        alias: tagList[tagIndex].text,
        id: editId,
      })
    } else {
      location.edit_save('0', user.id, {
        ...addressForm,
        isDefault: checked ? 1 : 0,
        gender: Number(addressForm.sex),
        alias: tagList[tagIndex].text,
      })
      setTimeout(() => {
        location.defaultaddress(user.id)
      }, 1000)
    }
    uni.navigateBack({
      delta: 1,
    })
  }).catch(err => {
    console.log('err', err)
  })
}
let tagIndex = $ref('0')
const tagList = [
  { id: '0', text: '家' },
  { id: '1', text: '公司' },
  { id: '2', text: '学校' },
  { id: '3', text: '其他' },
]
const changetagIndex = (index) => {
  tagIndex = index
}

let visible = $ref(false)
let maskCloseAble = $ref(true)
const confirm = (val) => {
  addressForm.address = val.name
  visible = false
}
const onCancel = val => visible = false
const open = () => {
  visible = true
}
const getIdByText = (data, searchText) => {
  const result = data.find(item => item.text === searchText)
  return result ? result.id : null
}
onMounted(async () => {
  if (edittype === '1') {
    const { data, error, status } = await Fetch(`/qqyapi/mall-member/user/address/get/${editId}`, {
      method: 'get',
      headers: {
        userId: user.id,
      },
    })
    if (status === 200 && data.code === 0) {
      const { lat, lon, detail, addressId, gender, isDefault, name, mobile, alias } = data.result
      location.updateLocation({
        latitude: lat,
        longitude: lon,
        detailAddress: detail,
        adcode: addressId,
      })
      tagIndex = getIdByText(tagList, alias)
      addressForm.sex = gender
      checked = isDefault !== 0
      addressForm.mobile = mobile
      addressForm.name = name
    }
  } else {
    location.getPosition({})
  }
})
</script>

<style lang="scss">
.add-address{
  .tabActive{
    color: #ABCD03;
    border: 1rpx solid #ABCD03;
  }

  .switch-color {
    color: #ABCD03;
  }

  .hide2 {
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 2;
    display: -webkit-box;
    -webkit-box-orient: vertical;
  }

  ::v-deep(.uni-switch-wrapper){
    .uni-switch-input{
      width: 112rpx;
      height: 58rpx;
      border-radius: 200rpx;
      background-color: #fff;
    }

    .uni-switch-input::after{
      height: 50rpx;
      width: 50rpx;
      left: 9px;
      top: 1px;
    }

    .uni-switch-input::before{
      width: 112rpx;
      height: 58rpx;
    }
  }

  ::v-deep(.uni-radio-wrapper){
    .uni-radio-input{
      background-color: #F5F5F5;
      border-color: transparent;
    }
  }

  ::v-deep(.uni-forms){
    .uni-forms-item{
      display: flex;
      flex-direction: row;
      align-items: center;
      margin-top: 0;
      margin-bottom: 0;
      padding-top: 22rpx;
      padding-bottom: 22rpx;
      box-sizing: border-box;

      .uni-forms-item__label{
        color: #333;
        font-size: 28rpx;
      }
    }
  }
}
</style>
